<template>
    <div class="common-layout">
        <el-container>
            <el-header>
                <el-form ref="formRef" :model="deptQureyform" label-width="auto" inline>
                    <el-form-item label="部门名称" prop="name">
                        <el-input
                            v-model="deptQureyform.name"
                            placeholder="请输入部门名称"
                            clearable
                        />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select
                            v-model="deptQureyform.status"
                            placeholder="请选择状态"
                            style="width: 170px"
                            clearable
                        >
                            <el-option
                                v-for="item in statusOptions.options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(formRef)">
                            <el-icon>
                                <ep-Search />
                            </el-icon>
                            <span>搜索</span>
                        </el-button>
                        <el-button @click="resetForm(formRef)">
                            <el-icon>
                                <ep-Refresh />
                            </el-icon>
                            <span>重置</span>
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-header>
            <el-main>
                <el-table :data="tableData" row-key="id" border default-expand-all stripe>
                    <el-table-column label="部门名称" prop="name" align="center" />
                    <el-table-column label="部门状态" align="center">
                        <template #default="scope">
                            <template v-if="showSwitchButton">
                                <el-switch
                                    v-model="scope.row.isUsed"
                                    size="large"
                                    inline-prompt
                                    active-text="启用"
                                    inactive-text="停用"
                                    :disabled="!hasPermission('system:dept:edit')"
                                    @change="handleStatusChange(scope.row)"
                                />
                            </template>
                            <template v-else>
                                <el-tag v-if="scope.row.status" type="success">
                                    {{ scope.row.statusDesc }}
                                </el-tag>
                                <el-tag v-else type="danger">
                                    {{ scope.row.statusDesc }}
                                </el-tag>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column label="显示顺序" prop="seqNo" align="center" />
                    <el-table-column label="创建人" prop="createBy" align="center" />
                    <el-table-column
                        label="创建时间"
                        prop="createTime"
                        align="center"
                        width="200"
                    />
                    <el-table-column label="操作" align="center" fixed="right">
                        <template #default="scope">
                            <el-tooltip
                                v-if="hasPermission('system:dept:detail')"
                                effect="dark"
                                content="查看详情"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    type="info"
                                    @click="handleDetail(scope.$index, scope.row)"
                                    link
                                >
                                    <el-icon><ep-Warning /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip
                                v-if="hasPermission('system:dept:add')"
                                effect="dark"
                                content="新增部门"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    type="default"
                                    @click="handleAdd(scope.$index, scope.row)"
                                    link
                                >
                                    <el-icon><ep-Plus /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip
                                v-if="hasPermission('system:dept:edit')"
                                effect="dark"
                                content="编辑部门"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    type="warning"
                                    @click="handleEdit(scope.$index, scope.row)"
                                    link
                                >
                                    <el-icon><ep-Edit /></el-icon>
                                </el-button>
                            </el-tooltip>
                            <el-tooltip
                                v-if="hasPermission('system:dept:remove')"
                                effect="dark"
                                content="删除部门"
                                placement="top"
                            >
                                <el-button
                                    size="small"
                                    type="danger"
                                    @click="handleDelete(scope.$index, scope.row)"
                                    link
                                >
                                    <el-icon><ep-Delete /></el-icon>
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
        </el-container>
        <div class="dialog-container">
            <add-dept />
            <edit-dept />
            <dept-detail />
        </div>
    </div>
</template>
<script setup name="Dept">
import { ref, reactive, computed, onActivated, nextTick, useTemplateRef, provide } from 'vue'
import addDept from './addDept.vue'
import editDept from './editDept.vue'
import deptDetail from './deptDetail.vue'
import { hasPermission } from '@/utils/common'
import { getDeptList, editDeptStatus, deleteDept } from '@/api/system/dept'
import { useRoute, useRouter } from 'vue-router'
import useStore from '@/stores'

const route = useRoute()
const router = useRouter()

const { settings } = useStore()

const showSwitchButton = computed(() => settings.showSwitchButton)

const addDeptVisible = ref(false)
const selectedRowId = ref(undefined)
const editDeptVisible = ref(false)
const selectedRow = ref({})
const deptDetailVisible = ref(false)

const formRef = useTemplateRef('formRef')
const tableData = ref([])
const statusOptions = reactive({
    options: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '0' }
    ]
})
const deptQureyform = reactive({
    name: undefined,
    status: undefined
})
const editDeptStatusform = reactive({
    id: undefined,
    status: undefined
})
provide('addDept', {
    addDeptVisible,
    selectedRowId
})
provide('editDept', {
    editDeptVisible,
    selectedRow
})
provide('deptDetail', {
    deptDetailVisible,
    selectedRow
})

/**
 *  部门详情
 * @param index   索引
 * @param row     行数据
 */
function handleDetail(index, row) {
    selectedRow.value = row
    deptDetailVisible.value = true
}

/**
 *  新增部门
 * @param index   索引
 * @param row     行数据
 */
function handleAdd(index, row) {
    selectedRowId.value = row.id
    addDeptVisible.value = true
}
/**
 * 编辑部门
 *  @param index   索引
 *  @param row     行数据
 */
function handleEdit(index, row) {
    selectedRow.value = row
    editDeptVisible.value = true
}
/**
 *  删除部门
 * @param index   索引
 * @param row     行数据
 */
function handleDelete(index, row) {
    ElMessageBox.confirm('确定执行删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    })
        .then(() => {
            deleteDept(row.id).then(() => {
                // 刷新表格
                const { query, path } = route
                router.replace({ path: '/redirect' + path, query: query })
            })
        })
        .catch(() => {})
}
/**
 * 提交表单
 */
function submitForm() {
    getDeptList(deptQureyform).then((response) => {
        if (response && response.data) {
            tableData.value = treeHandle(response.data)
        }
    })
}
/**
 *  修改部门状态
 * @param row    行数据
 */
function handleStatusChange(row) {
    editDeptStatusform.id = row.id
    editDeptStatusform.status = row.isUsed ? 1 : 0
    editDeptStatus(editDeptStatusform).then(() => {
        // 重置表单
        Object.keys(editDeptStatusform).forEach((key) => {
            editDeptStatusform[key] = undefined
        })
        // 刷新表格
        const { query, path } = route
        router.replace({ path: '/redirect' + path, query: query })
    })
}
/**
 * 处理部门数据，将其组织成树形结构，并且只有在对象有子元素时才添加 children 字段
 * @param {Array} data - 部门数据
 */
function treeHandle(data) {
    //把status转为boolean 用于swich开关显示,使用新的字段处理,防止影响到编辑页面或详情页面的显示
    data.forEach((item) => (item.isUsed = item.status === 1))
    // 遍历数据 找到当前对象的子元素
    let _children = []
    data.forEach((element) => {
        const children = data.filter((item) => element.id === item.parentId)
        if (children.length > 0) {
            // 将子节点添加到_children数组中
            _children.push(...children)
            element.children = children
        }
    })

    // 将_children转换为Set以提高查找效率
    const childrenSet = new Set(_children.map((child) => child.id))
    // 过滤掉那些已经在_children中的节点
    const filteredData = data.filter((item) => !childrenSet.has(item.id))

    return filteredData
}
/**
 * 重置表单
 * @param formEl 表单的ref
 */
function resetForm(formEl) {
    if (!formEl) return
    formEl.resetFields()
    submitForm()
}
// 在组件被激活时执行的操作
onActivated(() => {
    nextTick(() => {
        submitForm()
    })
})
</script>
<style lang="scss" scoped>
.common-layout {
    box-sizing: border-box;
    height: 100vh;
    padding: 20px;
    background-color: #f5f5f5;

    & .el-container {
        & .el-header {
            padding-top: 15px;
            @include flex-center();
            background-color: #fff;
        }

        & .el-main {
            padding: 0px;
            margin-top: 20px;
            // @include border($border-color:red);
            background-color: #e9eef3;
            color: #333;
        }
    }
}
</style>
